package servlet;

import com.google.gson.Gson;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class Control {
    //打印错误信息
    public static void fail(HttpServletResponse resp, String msg) throws IOException{
        Map<String,String> map=new HashMap<>();
        map.put("code","0");
        map.put("msg",msg);
        String json=new Gson().toJson(map);

        sendJson(resp,json);
    }
    public static void fail(HttpServletResponse resp) throws IOException{
        fail(resp,"操作失败");
    }

    //打印成功信息
    public static void success(HttpServletResponse resp) throws IOException{
        Map<String,String> map=new HashMap<>();
        map.put("code","1");
        String json=new Gson().toJson(map);

        sendJson(resp,json);
    }

    //发送json
    public static void sendJson(HttpServletResponse resp,String json) throws IOException{
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write(json);
    }

    //制作一个返回的json
    public static String buildJson(Object json){
        Map<String,Object> map=new HashMap<>();
        map.put("code","1");
        map.put("data",json);

        return new Gson().toJson(map);
    }

    //简单返回接口
    public static void simpleSend(boolean bool,HttpServletResponse resp)throws IOException{
        if(bool){
            success(resp);
        }else {
            fail(resp);
        }
    }
}
